<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="策略实例名称" prop="name">
        <el-select v-model="queryParams.name" placeholder="请选择或输入策略实例名称" clearable style="width: 200px" filterable
          allow-create @keyup.enter="handleQuery" @change="handleQuery">
          <el-option v-for="option in strategyInstanceOptions" :key="option.value" :label="option.label"
            :value="option.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button type="info" icon="ArrowRightBold" @click="handleNextInstance">遍历</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['kylin:strategyTradebook:add']">
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['kylin:strategyTradebook:edit']">
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['kylin:strategyTradebook:delete']">
          删除
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-row :gutter="20">
      <!-- 左侧表格区域 -->
      <el-col :span="10">
        <el-table v-loading="loading" :data="strategyTradebookList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="策略实例名称" align="center" prop="name" width="160" :show-overflow-tooltip="true" />
          <el-table-column label="价格" align="center" prop="price" width="80" :show-overflow-tooltip="true" />
          <el-table-column label="委托买入" align="center" prop="buy" width="80" :show-overflow-tooltip="true">
            <template #default="scope">
              {{ scope.row.buy === 0 ? '' : scope.row.buy }}
            </template>
          </el-table-column>
          <el-table-column label="委托卖出" align="center" prop="sell" width="80" :show-overflow-tooltip="true">
            <template #default="scope">
              {{ scope.row.sell === 0 ? '' : scope.row.sell }}
            </template>
          </el-table-column>
          <el-table-column label="已经买入" align="center" prop="bought" width="80" :show-overflow-tooltip="true">
            <template #default="scope">
              {{ scope.row.bought === 0 ? '' : scope.row.bought }}
            </template>
          </el-table-column>
          <el-table-column label="已经卖出" align="center" prop="sold" width="80" :show-overflow-tooltip="true">
            <template #default="scope">
              {{ scope.row.sold === 0 ? '' : scope.row.sold }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['kylin:strategyTradebook:edit']">修改
              </el-button>
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['kylin:strategyTradebook:delete']">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0 && !queryParams.name" :total="total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" @pagination="getList" />
      </el-col>

      <!-- 右侧可视化图表区域 -->
      <el-col :span="14">
        <div style="border: 1px solid #ebeef5; border-radius: 4px; padding: 10px; height: 100%;">
          <el-row :gutter="10">
            <el-col :span="24" style="display: flex; justify-content: space-between; align-items: center;">
              <h3 style="margin-bottom: 10px;">策略实例交易数据分析</h3>
              <el-button type="primary" plain icon="FullScreen" @click="handleFullScreen" style="float: right;">
                全屏显示
              </el-button>
            </el-col>
            <el-col :span="24" style="height: 600px;">
              <div id="priceByTradeTypeChart" style="width: 100%; height: 100%;"></div>
            </el-col>
          </el-row>
        </div>
      </el-col>

      <!-- 全屏显示对话框 -->
      <el-dialog v-model="fullScreenDialogVisible" :title="`策略实例交易数据分析 - 全屏显示 (${selectedInstanceName || '未选择实例'})`" width="90%" append-to-body
        destroy-on-close custom-class="full-screen-dialog">
        <div style="margin-bottom: 15px; display: flex; justify-content: flex-end;">
          <el-button type="info" icon="ArrowRightBold" @click="handleNextInstanceInFullScreen">遍历</el-button>
        </div>
        <div style="width: 100%; height: calc(100vh - 200px);">
          <div id="fullScreenChart" style="width: 100%; height: 100%;"></div>
        </div>
      </el-dialog>
    </el-row>

    <!-- 添加或修改策略交易登记簿对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="strategyTradebookRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="策略实例名称" prop="name">
          <el-select v-model="form.name" placeholder="请选择或输入策略实例名称" filterable allow-create>
            <el-option v-for="option in strategyInstanceOptions" :key="option.value" :label="option.label"
              :value="option.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model.number="form.price" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="委托买入" prop="buy">
          <el-input v-model.number="form.buy" placeholder="请输入委托买入数量" />
        </el-form-item>
        <el-form-item label="委托卖出" prop="sell">
          <el-input v-model.number="form.sell" placeholder="请输入委托卖出数量" />
        </el-form-item>
        <el-form-item label="已经买入" prop="bought">
          <el-input v-model.number="form.bought" placeholder="请输入已经买入数量" />
        </el-form-item>
        <el-form-item label="已经卖出" prop="sold">
          <el-input v-model.number="form.sold" placeholder="请输入已经卖出数量" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.full-screen-dialog {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 90vh;
}

.full-screen-dialog .el-dialog__wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 90vh;
}

.full-screen-dialog .el-dialog {
  max-height: 90vh;
  display: flex;
  flex-direction: column;
}

.full-screen-dialog .el-dialog__body {
  flex: 1;
  padding: 10px;
  overflow: hidden;
}
</style>

<script setup name="StrategyTradebook">
import { listFutureQuote, getWeightedAverageClosePrice } from '@/api/kylin/futureQuote';
import { listFutureStrategyInstance } from '@/api/kylin/futureStrategyInstance';
import {
  addStrategyTradebook,
  delStrategyTradebook,
  getStrategyTradebook,
  listStrategyTradebook,
  updateStrategyTradebook
} from '@/api/kylin/strategyTradebook';
import * as echarts from 'echarts';
import { getCurrentInstance, nextTick, onMounted, onUnmounted, reactive, ref, toRefs, watch } from 'vue';

const { proxy } = getCurrentInstance();

const strategyTradebookList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref('');

// 图表实例引用
const priceByTradeTypeChart = ref(null);
// 全屏图表实例引用
const fullScreenChartInstance = ref(null);
// 全屏对话框控制变量
const fullScreenDialogVisible = ref(false);
// 当前选中的策略实例名称
const selectedInstanceName = ref('');

// 行情数据相关
const futureQuoteData = ref([]);
const currentContractCode = ref('');
const loadingQuoteData = ref(false);
// 加权平均价格相关
const weightedAveragePrice20d = ref(null);

// 策略实例列表
const strategyInstanceOptions = ref([]);
// 遍历索引跟踪
const currentInstanceIndex = ref(-1); // -1表示尚未开始遍历

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined
  },
  rules: {
    name: [
      { required: true, message: '策略实例名称不能为空', trigger: 'blur' },
      { min: 1, max: 255, message: '策略实例名称长度不能超过255个字符', trigger: 'blur' }
    ],
    price: [
      { required: true, message: '价格不能为空', trigger: 'blur' },
      { type: 'number', message: '价格必须为数字值', trigger: 'blur' }
    ],
    buy: [
      { required: true, message: '委托买入不能为空', trigger: 'blur' },
      { type: 'number', message: '委托买入必须为数字值', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value < 0) {
            callback(new Error('委托买入数量不能为负数'));
          } else {
            callback();
          }
        }, trigger: 'blur'
      }
    ],
    sell: [
      { required: true, message: '委托卖出不能为空', trigger: 'blur' },
      { type: 'number', message: '委托卖出必须为数字值', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value < 0) {
            callback(new Error('委托卖出数量不能为负数'));
          } else {
            callback();
          }
        }, trigger: 'blur'
      }
    ],
    bought: [
      { required: true, message: '已经买入不能为空', trigger: 'blur' },
      { type: 'number', message: '已经买入必须为数字值', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value < 0) {
            callback(new Error('已经买入数量不能为负数'));
          } else {
            callback();
          }
        }, trigger: 'blur'
      }
    ],
    sold: [
      { required: true, message: '已经卖出不能为空', trigger: 'blur' },
      { type: 'number', message: '已经卖出必须为数字值', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value < 0) {
            callback(new Error('已经卖出数量不能为负数'));
          } else {
            callback();
          }
        }, trigger: 'blur'
      }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询策略交易登记簿列表 */
async function getList() {
  loading.value = true;

  try {
    // 创建一个查询参数的副本，避免直接修改响应式对象
    const params = { ...queryParams.value };

    // 如果有策略实例名称查询条件，则设置pageSize为一个很大的值以获取所有数据
    if (params.name) {
      params.pageSize = 9999;
    }

    const response = await listStrategyTradebook(params);

    // 统一响应数据处理逻辑
    const result = processApiResponse(response);
    strategyTradebookList.value = result.data;
    total.value = result.total;
  } catch (error) {
    console.error('查询数据失败:', error);
    strategyTradebookList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
}

/** 统一处理API响应数据 */
function processApiResponse(response) {
  if (response.rows && response.total) {
    return { data: response.rows, total: response.total };
  } else if (response.data) {
    const data = response.data || { rows: [], total: 0 };
    return { data: data.rows || [], total: data.total || 0 };
  }
  return { data: [], total: 0 };
}

/** 获取策略实例列表 */
async function loadStrategyInstanceList() {
  try {
    // 使用pageSize为一个较大的值来获取全部策略实例
    const response = await listFutureStrategyInstance({ pageSize: 9999, sortField: 'instance', sortOrder: 'asc' });

    // 根据实际响应格式获取数据
    if (response.data && response.data.rows && Array.isArray(response.data.rows)) {
      // 过滤出vtSymbol中包含&符号的套利合约实例
      const filteredInstances = response.data.rows.filter(isArbitrageContract);

      strategyInstanceOptions.value = filteredInstances.map(instance => ({
        value: instance.instance,
        label: instance.instance
      }));
    }
  } catch (error) {
    console.error('获取策略实例列表失败:', error);
  }
}

/** 判断是否为套利合约 */
function isArbitrageContract(item) {
  return item && item.vtSymbol && item.vtSymbol.includes('&');
}

/** 根据策略实例名称获取合约代码 */
async function getContractCodeByInstanceName(instanceName) {
  try {
    const response = await listFutureStrategyInstance({ instance: instanceName });
    // 根据实际响应格式获取数据
    if (response.data && response.data.rows && response.data.rows.length > 0) {
      return response.data.rows[0].vtSymbol;
    }
  } catch (error) {
    console.error('获取策略实例信息失败:', error);
  }
  return '';
}

/** 获取合约的交易行情数据 */
async function getFutureQuoteData(contractCode) {
  loadingQuoteData.value = true;

  try {
    // 验证合约代码
    if (!contractCode) {
      futureQuoteData.value = [];
      return;
    }

    // 设置查询参数
    const queryParams = {
      code: contractCode,
      pageSize: 9999
    };

    const response = await listFutureQuote(queryParams);

    // 处理响应数据并排序
    const rawData = extractQuoteData(response);
    futureQuoteData.value = rawData
      .sort((a, b) => new Date(a.date) - new Date(b.date))
      .map(formatQuoteData);


  } catch (error) {
    console.error('获取期货行情数据失败:', error);
    futureQuoteData.value = [];
  } finally {
    loadingQuoteData.value = false;
  }
}

/** 从响应中提取行情数据 */
function extractQuoteData(response) {
  if (response.rows && response.total) {
    return response.rows;
  } else if (response.data && response.data.rows) {
    return response.data.rows;
  } else if (Array.isArray(response.data)) {
    return response.data;
  } else if (Array.isArray(response)) {
    return response;
  }
  return [];
}

/** 格式化行情数据 */
function formatQuoteData(item) {
  return {
    date: item.date || new Date().toISOString().split('T')[0],
    close: Number(item.close || 0)
  };
}

/** 处理全屏显示 */
async function handleFullScreen() {
  // 显示全屏对话框
  fullScreenDialogVisible.value = true;

  // 等待对话框渲染完成
  await nextTick();

  // 初始化全屏图表
  await initFullScreenChart();
}

/** 全屏模式下遍历下一个策略实例时更新图表数据 */
async function updateFullScreenChart() {
  try {
    // 验证必要的图表实例
    if (!fullScreenChartInstance.value || !priceByTradeTypeChart.value) {
      console.error('全屏图表实例或原图表实例不存在');
      return;
    }

    // 获取并优化图表配置
    const originalOption = priceByTradeTypeChart.value.getOption();
    const fullScreenOption = optimizeChartOptionForFullScreen(originalOption);

    // 应用配置到图表
    fullScreenChartInstance.value.setOption(fullScreenOption, true);

    // 设置大小调整监听和对话框关闭清理
    setupChartEventListeners();
  } catch (error) {
    console.error('更新全屏图表失败:', error);
  }
}

/** 初始化全屏图表 */
async function initFullScreenChart() {
  try {
    // 确保DOM渲染完成
    await nextTick();

    // 获取并验证DOM元素
    const chartDom = document.getElementById('fullScreenChart');
    if (!chartDom) {
      console.error('全屏图表容器不存在');
      return;
    }

    // 销毁旧的图表实例
    disposeChartInstance(fullScreenChartInstance);

    // 初始化新图表实例
    fullScreenChartInstance.value = createChartInstance(chartDom);

    // 设置初始配置
    if (fullScreenChartInstance.value) {
      const initialOption = createInitialChartOption();
      fullScreenChartInstance.value.setOption(initialOption, true);

      // 更新全屏图表数据
      await updateFullScreenChart();
    }
  } catch (error) {
    console.error('初始化全屏图表失败:', error);
  }
}



/** 销毁图表实例 */
function disposeChartInstance(chartRef) {
  if (chartRef.value) {
    try {
      chartRef.value.dispose();
    } catch (err) {
      console.error('销毁图表实例失败:', err);
    }
    chartRef.value = null;
  }
}

/** 创建图表实例 */
function createChartInstance(domElement) {
  // 确保echarts库已正确加载
  if (!window.echarts && !echarts) {
    console.error('ECharts库未正确加载');
    return null;
  }

  const ecLib = window.echarts || echarts;
  return ecLib.init(domElement);
}

/** 创建初始图表配置 */
function createInitialChartOption() {
  return {
    grid: {
      left: '3%',
      right: '3%',
      bottom: '10%',
      top: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['初始化中...']
    },
    yAxis: {
      type: 'value',
      scale: true
    },
    series: []
  };
}

/** 优化图表配置以适应全屏显示 */
function optimizeChartOptionForFullScreen(originalOption) {
  // 深拷贝原始配置
  const optimizedOption = JSON.parse(JSON.stringify(originalOption));

  // 优化布局
  if (optimizedOption.grid) {
    optimizedOption.grid.left = '3%';
    optimizedOption.grid.right = '3%';
    optimizedOption.grid.bottom = '10%';
    optimizedOption.grid.top = '10%';
  }

  // 优化坐标轴标签
  if (optimizedOption.xAxis && optimizedOption.xAxis[0]) {
    optimizedOption.xAxis[0].axisLabel = {
      interval: 0,
      rotate: 45,
      fontSize: 14
    };
  }

  if (optimizedOption.yAxis && optimizedOption.yAxis[0]) {
    optimizedOption.yAxis[0].axisLabel = {
      fontSize: 14
    };
  }

  // 优化提示框
  if (optimizedOption.tooltip) {
    optimizedOption.tooltip.textStyle = {
      fontSize: 14
    };
  }

  return optimizedOption;
}

/** 设置图表事件监听器 */
function setupChartEventListeners() {
  // 窗口大小变化监听
  const handleResize = () => {
    if (fullScreenChartInstance.value) {
      fullScreenChartInstance.value.resize();
    }
  };

  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize);

  // 设置对话框关闭时的清理逻辑
  setupDialogCloseCleanup(handleResize);
}

/** 设置对话框关闭时的清理逻辑 */
function setupDialogCloseCleanup(resizeHandler) {
  const cleanup = () => {
    // 移除窗口大小变化监听
    window.removeEventListener('resize', resizeHandler);

    // 销毁图表实例
    disposeChartInstance(fullScreenChartInstance);

    // 断开观察器连接
    if (window._fullScreenDialogObserver) {
      window._fullScreenDialogObserver.disconnect();
      window._fullScreenDialogObserver = null;
    }
  };

  // 创建对话框关闭观察器
  const observer = new MutationObserver((mutations) => {
    for (const mutation of mutations) {
      if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
        const dialogWrapper = document.querySelector('.el-dialog__wrapper[aria-modal="true"]');
        if (dialogWrapper && dialogWrapper.style.display === 'none') {
          cleanup();
        }
      }
    }
  });

  // 保存观察器引用
  window._fullScreenDialogObserver = observer;

  // 开始观察对话框样式变化
  const dialogElement = document.querySelector('.el-dialog__wrapper[aria-modal="true"]');
  if (dialogElement) {
    observer.observe(dialogElement, { attributes: true });
  }
}

/** 初始化价格按日期分析图 */
async function initPriceByTradeTypeChart() {
  try {
    // 获取并验证DOM元素
    const chartDom = document.getElementById('priceByTradeTypeChart');
    if (!chartDom) {
      console.error('价格分析图DOM元素不存在');
      return;
    }

    // 销毁旧的图表实例
    disposeChartInstance(priceByTradeTypeChart);

    // 创建新的图表实例
    priceByTradeTypeChart.value = createChartInstance(chartDom);

    if (priceByTradeTypeChart.value) {
      // 设置初始配置
      const initialOption = createInitialChartOption();
      priceByTradeTypeChart.value.setOption(initialOption, true);

      // 更新图表数据
      await updatePriceByTradeTypeChart();
    }
  } catch (error) {
    console.error('初始化价格分析图失败:', error);
    priceByTradeTypeChart.value = null;
  }
}

/** 获取合约特定天数的加权平均价格 */
async function getContractWeightedAveragePrice(contractCode, days) {
  try {
    const response = await getWeightedAverageClosePrice(contractCode, days);
    if (response && response.data) {
      weightedAveragePrice20d.value = response.data;
    } else {
      weightedAveragePrice20d.value = null;
    }
  } catch (error) {
    console.error(`获取合约${contractCode}最近${days}天的加权平均价格时发生错误:`, error);
    weightedAveragePrice20d.value = null;
  }
}

/** 更新价格按日期分析图数据 */
async function updatePriceByTradeTypeChart() {
  try {
    // 确保图表实例存在
    if (!priceByTradeTypeChart.value) {
      await initPriceByTradeTypeChart();
      // 给初始化一些时间完成
      await new Promise(resolve => setTimeout(resolve, 100));

      if (!priceByTradeTypeChart.value) {
        console.error('图表重新初始化失败，无法更新图表数据');
        return;
      }
    }

    // 使用搜索框中的策略实例名称进行筛选
    const searchName = queryParams.value.name;
    const filteredData = filterStrategyData(strategyTradebookList.value, searchName);

    // 如果有筛选数据，获取对应的合约代码和行情数据
    let contractCode = '';
    if (filteredData.length > 0 && filteredData[0].name) {
      try {
        contractCode = await getContractCodeByInstanceName(filteredData[0].name);
        if (contractCode) {
          // 总是重新获取行情数据，确保数据是最新的
          currentContractCode.value = contractCode;
          await getFutureQuoteData(contractCode);
          // 获取该合约20日的加权平均价格
          await getContractWeightedAveragePrice(contractCode, 60);
        }
      } catch (error) {
        console.error('获取合约代码或行情数据失败:', error);
      }
    }

    // 确保futureQuoteData.value是数组
    if (!Array.isArray(futureQuoteData.value)) {
      futureQuoteData.value = [];
    }

    // 深度检查数据是否有效
    const hasValidData = hasAnyValidDataPoint(futureQuoteData.value);
    if (!hasValidData) {
      futureQuoteData.value = [];
    }

    // 处理图表数据
    const { xAxisData, seriesData, markPoints } = processChartData(futureQuoteData.value, strategyTradebookList.value);

    // 检查是否有有效数据点
    const hasChartData = xAxisData.length > 0 && seriesData.length > 0;

    // 创建图表配置
    const chartOption = hasChartData
      ? createChartOptionWithData(xAxisData, seriesData, markPoints, weightedAveragePrice20d.value)
      : createEmptyChartOption();

    // 设置图表配置
    updateChartWithOption(priceByTradeTypeChart.value, chartOption);
  } catch (error) {
    console.error('更新图表数据失败:', error);
    // 出现任何异常时，尝试显示一个空图表
    if (priceByTradeTypeChart.value) {
      try {
        const emptyOption = createEmptyChartOption();
        priceByTradeTypeChart.value.setOption(emptyOption, true);
      } catch (emptyError) {
        console.error('显示空图表失败:', emptyError);
      }
    }
  }
}

/** 筛选策略数据 */
function filterStrategyData(data, searchName) {
  if (searchName) {
    return data.filter(item => item.name && item.name.includes(searchName));
  } else {
    // 如果没有搜索条件，默认显示第一个策略实例的数据
    const firstInstanceName = data[0]?.name;
    if (firstInstanceName) {
      return data.filter(item => item.name === firstInstanceName);
    }
  }
  return data;
}

/** 检查是否有有效的数据点 */
function hasAnyValidDataPoint(data) {
  if (!data || !Array.isArray(data) || data.length === 0) {
    return false;
  }

  return data.some(item =>
    item && typeof item === 'object' && item.date &&
    item.close !== undefined && item.close !== null && !isNaN(Number(item.close))
  );
}

/** 处理图表数据 */
function processChartData(quoteData, tradebookData) {
  // 创建纯净的数据数组
  const chartData = createCleanDataArray(quoteData);

  // 数据抽样和光滑化处理
  const processedData = preprocessChartData(chartData);

  // 准备X轴和Series数据
  const { xAxisData, seriesData } = prepareChartAxisData(processedData);

  // 准备交易数据标记点
  const markPoints = createMarkPoints(tradebookData, xAxisData);

  return { xAxisData, seriesData, markPoints };
}

/** 创建纯净的数据数组 */
function createCleanDataArray(data) {
  const cleanData = [];

  for (let i = 0; i < data.length; i++) {
    const item = data[i];
    if (item && typeof item === 'object' && item.date &&
      item.close !== undefined && item.close !== null && !isNaN(Number(item.close))) {
      cleanData.push({
        date: String(item.date),
        close: Number(item.close)
      });
    }
  }

  return cleanData;
}

/** 预处理图表数据（抽样和光滑化） */
function preprocessChartData(data) {
  const MAX_DATA_POINTS = 100;
  let processedData = [];
  if (Array.isArray(data)) {
    processedData = data.slice();
  }

  // 抽样处理
  if (processedData.length > MAX_DATA_POINTS) {
    processedData = sampleChartData(processedData, MAX_DATA_POINTS);
  }

  // 光滑化处理
  const WINDOW_SIZE = 3;
  if (processedData.length >= WINDOW_SIZE * 2) {
    processedData = smoothChartData(processedData, WINDOW_SIZE);
  }

  return processedData;
}

/** 数据抽样 */
function sampleChartData(data, maxPoints) {
  const sampleRate = Math.ceil(data.length / maxPoints);
  const sampledData = [];

  // 等间隔抽样，保留首尾数据点
  for (let i = 0; i < data.length; i += sampleRate) {
    sampledData.push(data[i]);
  }

  // 确保最后一个数据点也被保留
  if (sampledData.length > 0 &&
    sampledData[sampledData.length - 1].date !== data[data.length - 1].date) {
    sampledData.push(data[data.length - 1]);
  }

  return sampledData;
}

/** 数据光滑化 */
function smoothChartData(data, windowSize) {
  const smoothedData = [];

  // 保留第一个数据点
  smoothedData.push({ ...data[0] });

  // 对中间数据点进行移动平均处理
  for (let i = 1; i < data.length - 1; i++) {
    // 确保窗口内有足够的数据点
    const startIdx = Math.max(0, i - Math.floor(windowSize / 2));
    const endIdx = Math.min(data.length, i + Math.ceil(windowSize / 2));

    // 计算窗口内的平均值
    let sum = 0;
    let count = 0;

    for (let j = startIdx; j < endIdx; j++) {
      sum += data[j].close;
      count++;
    }

    // 创建光滑后的数据点，保留原始日期
    smoothedData.push({
      date: data[i].date,
      close: parseFloat((sum / count).toFixed(2))
    });
  }

  // 保留最后一个数据点
  smoothedData.push({ ...data[data.length - 1] });

  return smoothedData;
}

/** 准备图表轴数据 */
function prepareChartAxisData(data) {
  const xAxisData = [];
  const seriesData = [];

  for (let i = 0; i < data.length; i++) {
    xAxisData.push(String(data[i].date));
    seriesData.push(Number(data[i].close));
  }

  return { xAxisData, seriesData };
}

/** 创建交易标记点 */
function createMarkPoints(tradebookData, xAxisData) {
  const markPoints = [];

  // 仅在有交易数据且数据量合适时添加标记点
  if (!tradebookData || tradebookData.length === 0 || xAxisData.length < 4) {
    return markPoints;
  }

  // 选择中间的4个日期作为标记点的横坐标
  const middleIndex = Math.floor(xAxisData.length / 2);

  // 为不同类型的交易创建标记点配置
  const markPointTypes = [
    { key: 'buy', name: '委托买入', symbol: 'circle', symbolSize: 15, itemStyle: { color: '#b7eb8f' } },
    { key: 'sell', name: '委托卖出', symbol: 'circle', symbolSize: 15, itemStyle: { color: '#ffccc7' } },
    { key: 'bought', name: '已经买入', symbol: 'circle', symbolSize: 15, itemStyle: { color: '#52c41a' } },
    { key: 'sold', name: '已经卖出', symbol: 'circle', symbolSize: 15, itemStyle: { color: '#ff7875' } }
  ];

  // 遍历交易数据，创建标记点
  for (let i = 0; i < tradebookData.length; i++) {
    const tradeItem = tradebookData[i];

    // 遍历不同类型的交易标记
    for (let j = 0; j < markPointTypes.length; j++) {
      const typeConfig = markPointTypes[j];
      const value = tradeItem[typeConfig.key];

      // 只添加值大于等于1的标记点
      if (value !== undefined && value !== null && Number(value) >= 1) {
        markPoints.push(createSingleMarkPoint(tradeItem, typeConfig, middleIndex, xAxisData, i, j, value));
      }
    }
  }

  return markPoints;
}

/** 创建单个标记点 */
function createSingleMarkPoint(tradeItem, typeConfig, middleIndex, xAxisData, tradeIndex, typeIndex, value) {
  // 根据交易类型设置不同的横坐标偏移
  let offset;
  if (typeIndex === 0 || typeIndex === 1) { // 委托买入或委托卖出
    offset = -10 + typeIndex * 3; // 更大幅度向左移动
  } else { // 已经买入或已经卖出
    offset = 7 + (typeIndex - 2) * 6; // 更大幅度向右移动
  }

  const dateIndex = Math.max(0, Math.min(xAxisData.length - 1, middleIndex + offset));
  const markerDate = xAxisData[dateIndex];

  // 为了进一步避免重叠，根据类型和交易项索引调整价格位置
  const basePrice = Number(tradeItem.price || 0);
  // 根据类型调整基础价格偏移量
  const typeOffset = (typeIndex - 1.5) * 1.5;
  // 根据交易项索引添加微小的随机偏移量
  const randomOffset = (tradeIndex % 3 - 1) * 0.4;
  const markerPrice = basePrice + typeOffset + randomOffset;

  return {
    name: typeConfig.name,
    value: String(value),
    coord: [markerDate, markerPrice],
    symbol: typeConfig.symbol,
    symbolSize: typeConfig.symbolSize,
    itemStyle: typeConfig.itemStyle,
    label: {
      show: true,
      formatter: String(value),
      position: 'inside',
      color: '#fff',
      fontSize: 10,
      fontWeight: 'bold'
    }
  };
}

/** 创建有数据的图表配置 */
function createChartOptionWithData(xAxisData, seriesData, markPoints, weightedAvgPrice) {
  return {
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(0,0,0,0.7)',
      borderColor: '#5470c6',
      textStyle: { color: '#fff' }
    },
    legend: {
      data: ['收盘价'],
      show: true
    },
    grid: {
      left: '5%',
      right: '5%',
      bottom: '20%',
      top: '20%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: xAxisData,
      axisLabel: { interval: 0, rotate: 45 }
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      name: '收盘价',
      type: 'line',
      smooth: true,
      data: seriesData,
      markPoint: {
        data: markPoints,
        symbolSize: function (val) {
          // 根据值的大小调整标记点大小
          const numVal = Number(val[0]);
          return Math.max(30, Math.min(60, 30 + numVal * 2));
        }
      },
      markLine: weightedAvgPrice ? {
        silent: true,
        lineStyle: {
          color: '#ff7875',
          type: 'dashed',
          width: 1
        },
        label: {
          formatter: '60日加权平均: ' + weightedAvgPrice.toFixed(2),
          position: 'middle',
          distance: -10,
          color: '#ff7875'
        },
        symbol: 'none',
        data: [{ yAxis: weightedAvgPrice }]
      } : undefined
    }]
  };
}

/** 创建空图表配置 */
function createEmptyChartOption() {
  return {
    grid: {
      left: '5%',
      right: '5%',
      bottom: '15%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['暂无有效数据']
    },
    yAxis: {
      type: 'value'
    },
    series: []
  };
}

/** 更新图表配置 */
function updateChartWithOption(chartInstance, option) {
  if (!chartInstance) {
    console.error('图表实例不存在');
    return;
  }

  // 清除之前的内容
  chartInstance.clear();

  // 设置图表配置
  try {
    chartInstance.setOption(option, true);
  } catch (error) {
    console.error('设置图表配置失败:', error);
    // 显示一个非常基础的错误提示图表
    try {
      const errorOption = createEmptyChartOption();
      chartInstance.setOption(errorOption, true);
    } catch (innerError) {
      console.error('显示错误图表也失败:', innerError);
    }
  }
}

/** 初始化所有图表 */
async function initCharts() {
  try {
    // 初始化价格按日期分析图表
    await initPriceByTradeTypeChart();
  } catch (error) {
    console.error('初始化图表失败:', error);
  }
}

/** 页面加载时初始化图表 */
onMounted(async () => {
  try {
    // 先获取策略实例列表
    await loadStrategyInstanceList();
    // 获取策略交易数据
    await getList();
    // 等待DOM渲染完成
    await nextTick();
    // 初始化图表
    await initCharts();
    // 添加窗口大小改变时的响应
    window.addEventListener('resize', handleResize);
  } catch (error) {
    console.error('页面初始化失败:', error);
  }
});

/** 窗口大小改变时调整图表大小 */
function handleResize() {
  try {
    // 调整所有活跃图表的大小
    resizeAllCharts();
  } catch (error) {
    console.error('调整图表大小失败:', error);
  }
}

/** 调整所有图表大小 */
function resizeAllCharts() {
  // 调整价格分析图表大小
  if (priceByTradeTypeChart.value) {
    priceByTradeTypeChart.value.resize();
  }

  // 调整全屏图表大小（如果存在）
  if (fullScreenChart.value) {
    fullScreenChart.value.resize();
  }

  // 调整全屏图表实例大小（如果存在）
  if (fullScreenChartInstance.value) {
    fullScreenChartInstance.value.resize();
  }
}

/** 页面卸载时清理资源 */
onUnmounted(() => {
  // 移除窗口大小改变事件监听
  window.removeEventListener('resize', handleResize);
  // 销毁图表实例
  if (priceByTradeTypeChart.value) {
    priceByTradeTypeChart.value.dispose();
    priceByTradeTypeChart.value = null;
  }
});

/** 更新所有图表数据 */
async function updateCharts() {
  try {
    // 更新价格按日期分析图表
    await updatePriceByTradeTypeChart();
  } catch (error) {
    console.error('更新图表失败:', error);
  }
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {};
  proxy.resetForm('strategyTradebookRef');
}

/** 遍历下一个策略实例 */
async function handleNextInstance() {
  // 确保策略实例列表已加载
  if (!strategyInstanceOptions.value || strategyInstanceOptions.value.length === 0) {
    proxy.$modal.msgWarning('策略实例列表为空，无法遍历');
    return;
  }

  // 如果是第一次遍历，从第一个开始
  if (currentInstanceIndex.value === -1) {
    currentInstanceIndex.value = 0;
  } else {
    // 检查是否到达最后一个实例
    if (currentInstanceIndex.value === strategyInstanceOptions.value.length - 1) {
      // 提示已经到达最后一个，然后循环到第一个
      proxy.$modal.msgInfo('已经查询到最后一个策略实例，现在查询第一个策略实例');
      currentInstanceIndex.value = 0;
    } else {
      // 移动到下一个实例
      currentInstanceIndex.value++;
    }
  }

  // 获取当前策略实例
  const currentInstance = strategyInstanceOptions.value[currentInstanceIndex.value];
  if (currentInstance) {
    // 更新查询参数
    queryParams.value.name = currentInstance.value;
    // 更新选中的策略实例名称
    selectedInstanceName.value = currentInstance.label;
    // 执行查询
    await handleQuery();
  }
}

/** 全屏模式下遍历下一个策略实例 */
async function handleNextInstanceInFullScreen() {
  await handleNextInstance();
  await updateFullScreenChart();
  // 标题会自动更新，因为selectedInstanceName是响应式的
}

/** 搜索按钮操作 */
async function handleQuery() {
  queryParams.value.pageNum = 1;
  // 当用户通过搜索按钮进行查询时，如果不是通过遍历函数触发的，重置遍历索引
  // 这里简单判断：如果当前查询的实例名称不在当前索引位置，说明是通过其他方式查询的
  const currentInstance = strategyInstanceOptions.value[currentInstanceIndex.value];
  if (currentInstance && currentInstance.value !== queryParams.value.name) {
    currentInstanceIndex.value = -1;
  }
  
  // 更新选中的策略实例名称
  if (queryParams.value.name) {
    const selectedOption = strategyInstanceOptions.value.find(option => option.value === queryParams.value.name);
    if (selectedOption) {
      selectedInstanceName.value = selectedOption.label;
    } else {
      selectedInstanceName.value = queryParams.value.name;
    }
  } else {
    selectedInstanceName.value = '';
  }
  
  await getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef');
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = '添加策略交易登记簿';
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const tradebookId = row.id || ids.value;
  getStrategyTradebook(tradebookId).then(response => {
    // 检查响应数据结构并正确赋值
    if (response && response.data) {
      form.value.id = response.data.id;
      form.value.name = response.data.name;
      form.value.price = response.data.price;
      form.value.buy = response.data.buy;
      form.value.sell = response.data.sell;
      form.value.bought = response.data.bought;
      form.value.sold = response.data.sold;
    }
    open.value = true;
    title.value = '修改策略交易登记簿';
  }).catch(error => {
    console.error('获取单个策略交易登记簿数据失败:', error);
  });
}

/** 提交按钮 */
function submitForm() {
  // 确保表单数据完整性
  if (!form.value.name) {
    form.value.name = '';
  }
  if (form.value.price === undefined || form.value.price === null) {
    form.value.price = 0;
  }
  if (form.value.buy === undefined || form.value.buy === null) {
    form.value.buy = 0;
  }
  if (form.value.sell === undefined || form.value.sell === null) {
    form.value.sell = 0;
  }
  if (form.value.bought === undefined || form.value.bought === null) {
    form.value.bought = 0;
  }
  if (form.value.sold === undefined || form.value.sold === null) {
    form.value.sold = 0;
  }

  proxy.$refs['strategyTradebookRef'].validate(valid => {
    if (valid) {
      if (form.value.id) {
        updateStrategyTradebook(form.value.id, form.value).then(response => {
          proxy.$modal.msgSuccess('修改成功');
          open.value = false;
          getList();
        }).catch(error => {
          console.error('修改失败:', error);
          proxy.$modal.msgError('修改失败，请重试');
        });
      } else {
        addStrategyTradebook(form.value).then(response => {
          proxy.$modal.msgSuccess('新增成功');
          open.value = false;
          getList();
        }).catch(error => {
          console.error('新增失败:', error);
          proxy.$modal.msgError('新增失败，请重试');
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const tradebookIds = row.id ? [row.id] : ids.value;
  proxy.$modal.confirm('是否确认删除策略交易登记簿？').then(() => {
    return delStrategyTradebook(tradebookIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess('删除成功');
  }).catch(() => {
  });
}

// 监听数据变化，更新图表
watch(() => strategyTradebookList.value, async () => {
  await updateCharts();
}, { deep: true });

// 监听搜索框变化，更新图表
watch(() => queryParams.value.name, async () => {
  await updateCharts();
});
</script>